/**
 * 课程11 封装简易地图框架
 *
 */
// 框架

/**
 * 1 支持自定义图层 点 线 面
 * 2 点击 点线面 可以弹出 popup 气泡
 * 3 用更好的面向对象语法 去抽离  js  class
 * 4 图层支持 隐藏 及 出现
 * 5 图层支持 设置 zoom
 */

mapboxgl.accessToken = 'pk.eyJ1IjoiNGgzajgiLCJhIjoiY202cTRneXdpMDlheDJpb21rdGs2M3V6cSJ9.Ifg4pD0p8LxYmxmxwoTBNA';

const map = (window.map = new mapboxgl.Map({
  container: 'map',
  center: [121.74380266722233, 31.097567372835357],
  zoom: 10,
  minZoom: 10,
  maxZoom: 21,
  optimizeForTerrain: false,
  preserveDrawingBuffer: true,
}));


map.on('load', () => {
  map.addSource('radar', {
    'type': 'image',
    'url': 'https://docs.mapbox.com/mapbox-gl-js/assets/radar.gif',
    'coordinates': [
      [-80.425, 46.437],
      [-71.516, 46.437],
      [-71.516, 37.936],
      [-80.425, 37.936]
    ]
  });
  map.addLayer({
    id: 'radar-layer',
    'type': 'raster',
    'source': 'radar',
    'paint': {
      'raster-fade-duration': 0,
      'raster-emissive-strength': 1
    }
  });

  // 地图创建完成 发送到全局
  let mapCreatedEvent = new CustomEvent("mapCreatedEvent", {
    detail: {
      map,
    },
  });

  // 发送到全局
  window.dispatchEvent(mapCreatedEvent);
})
map.on('click', (ev) => {
  console.log([ev.lngLat.lng, ev.lngLat.lat])

  let layerMap = []
  window.layerManager.forEach(item => {
    layerMap.push(item.name)
  })
  console.log(layerMap)

  const feature = map.queryRenderedFeatures(ev.point, {
    layers: layerMap
  });

  if (feature && feature.length) {
    let f = feature[0]
    let layerId = f.layer.id
    let data = f.properties.data
    if (data) {
      let object_json_data = JSON.parse(data)

      console.log(layerId, object_json_data)

      // 获取图层
      let layer = window.layerManager.get(layerId)
      let position = [ev.lngLat.lng, ev.lngLat.lat]
      if (f.geometry.type === 'Point') {
        position = f.geometry.coordinates
      }
      // 调用图层的showTip 方法
      if (!layer.noneTips) {
        layer.showTip({
          position,
          feature: f,
          data: object_json_data
        })
      }

    }
    console.log(f)
  }



})
